package des;

import dySec.GetOTP;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;


public class MainFrame extends Application {

    private String key;  //密钥
    private int c;  //事件因子
    private long T;
    private TextField codeInput; //输入框

    //测试结果文本框
    public Label info,info1;

    public MainFrame(long Time, int cstr, String genKey) {
        this.T = Time;
        this.c = cstr;
        this.key = genKey;
    }

    /**
     * 启动程序
     */
    public static void main(String[] args) {
        launch(args);
    }

    /**
     * 启动界面
     */
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("动态口令生成");
            //界面布局
            GridPane grid = new GridPane();
            grid.setAlignment(Pos.CENTER);
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(25,25,25,25));

            Label initPrompt = new Label("动态口令生成：");
            grid.add(initPrompt,0,0,2,1);

            Label initNumLabel = new Label("验证码");
            grid.add(initNumLabel,0,1);

            codeInput = new TextField();
            grid.add(codeInput,1,1);

            grid.add(new Label("动态口令"),0,2);
            info = new Label();
            grid.add(info,1,2);

            Button startBtn = new Button("生成口令");
            startBtn.setOnAction(actionEvent -> buildOpt());
            grid.add(startBtn,1,3);

            info1 = new Label();
            grid.add(info1,1,4);

            Scene scene = new Scene(grid,400,300);
            primaryStage.setScene(scene);
            primaryStage.show();
            primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

                @Override
                public void handle(WindowEvent event) {
                    System.out.println("MainFrame setOnCloseRequest");
                    //PropUtils.saveConfig();
                }
            });
    }

    /**
     * 生成动态口令
     *
     */
    private void buildOpt() {
        System.out.println("T = " + T);
        System.out.println("C = " + c);
        String code=codeInput.getText();
        if (code==null || "".equals(code)) {
            info1.setText("请输入验证码！");
            return;
        }
        if (code.length()!=4) {
            info1.setText("验证码应为4位！");
            return;
        }
        //加密密钥key
        GetOTP OTP = new GetOTP();
        String P = OTP.getOTP(T, c, code, key);
        info.setText(P);
        PropUtils.saveConfig(1);
    }
}
